import {useAuthStore} from "@/store/modules/auth";
import {AxiosRequestConfig,} from "axios";
// import camelcaseKeys from "camelcase-keys";
// import snakeCaseKeys from "snake-keys";
import Axios from "./axios";

const createAxios = () => {
	return new Axios({
		baseURL: import.meta.env.VITE_APP_BASE_API,
		timeout: 1000 * 60 * 5,
		interceptors: {
			requestInterceptor: (config: AxiosRequestConfig) => {
				if (!config) {
					config = {}
				}
				if (!config.headers) {
					config.headers = {}
				}
				const token = useAuthStore().token
				if (token) {
					config.headers.Authorization = `Bearer ${token}`
				}
				// if (config.data) {
				// 	config.data = snakeCaseKeys(config.data as Object, {deep: true})
				// }
				// get请求映射params参数
				if ((config.method === 'get' || config.method === 'GET') && config.params) {
					// config.params = snakeCaseKeys(config.params as Object, {deep: true})
					let url = config.url + '?'
					for (const propName of Object.keys(config.params)) {
						const value = config.params[propName]
						const part = encodeURIComponent(propName) + '='
						if (value !== null && typeof (value) !== 'undefined') {
							if (typeof value === 'object') {
								for (const key of Object.keys(value)) {
									let params = propName + '[' + key + ']'
									const subPart = encodeURIComponent(params) + '='
									url += subPart + encodeURIComponent(value[key]) + '&'
								}
							} else {
								url += part + encodeURIComponent(value) + '&'
							}
						}
					}
					url = url.slice(0, -1)
					config.params = {}
					config.url = url
				}
				return config
			},
		}
	})
}
export const defHttp = createAxios();
